<template>
  <div class="chat-container">
    <div class="topbar">
      <el-button @click="$router.back()" circle><el-icon><back /></el-icon></el-button>
      <div class="agent-name">{{ agentName }}</div>
      <div class="spacer"></div>
    </div>
    
    <div class="chat-main">
      <!-- 左侧会话列表 -->
      <aside class="sessions-sidebar">
        <div class="section-header">
          <span>会话</span>
          <el-button @click="handleNewSession" circle size="small" title="新建会话">
            <el-icon><plus /></el-icon>
          </el-button>
        </div>
        <div class="sessions-list">
          <div
            v-for="session in sessions"
            :key="session.id"
            class="session-item"
            :class="{ active: currentSessionId === session.id }"
            @click="switchSession(session.id)"
            @dblclick="handleRenameSession(session)"
          >
            <span class="session-title">{{ session.title }}</span>
          </div>
        </div>
      </aside>
      
      <!-- 中间对话区域 -->
      <main class="chat-area">
        <div class="messages" ref="messagesRef" @scroll="handleScroll">
          <div v-if="hasMore && !loadingMore" class="load-more-trigger" ref="loadMoreTriggerRef">
            <el-button text @click="loadMoreMessages">加载更多历史消息</el-button>
          </div>
          <div v-if="loadingMore" class="loading-more">
            <el-icon class="is-loading"><loading /></el-icon> 加载中...
          </div>
          <div v-for="msg in messages" :key="msg.id" class="msg-line" :class="{ me: msg.role === 'user' }">
            <div class="msg-avatar" :class="msg.role">
              {{ msg.role === 'user' ? '我' : agentIcon }}
            </div>
            <div class="bubble" :class="getBubbleClass(msg)" v-html="renderMarkdown(msg.content)"></div>
          </div>
          
          <div v-if="streaming" class="msg-line">
            <div class="msg-avatar agent">{{ agentIcon }}</div>
            <div class="bubble streaming">
              <span v-html="renderMarkdown(streamingContent)"></span>
              <span class="cursor">|</span>
            </div>
          </div>
        </div>
        
        <div class="composer">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="输入你的问题，Enter 发送 / Shift+Enter 换行"
            @keydown.enter="handleSend"
          />
          <el-button
            type="primary"
            @click="handleSend"
            :loading="streaming"
            :disabled="!inputMessage.trim()"
          >
            生成
          </el-button>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Back, Plus, Loading } from '@element-plus/icons-vue'
import { getAgentDetail } from '@/api/agent'
import { createSession, getSessions, getMessages, updateSession } from '@/api/session'
import { marked } from 'marked'
import hljs from 'highlight.js'

const route = useRoute()
const router = useRouter()

const agentId = computed(() => parseInt(route.params.agentId))
const agentName = ref('')
const agentIcon = ref('A')

const sessions = ref([])
const currentSessionId = ref(null)
const messages = ref([])
const inputMessage = ref('')
const streaming = ref(false)
const streamingContent = ref('')

const messagesRef = ref(null)
const loadMoreTriggerRef = ref(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const hasMore = ref(false)
const loadingMore = ref(false)
const isFirstLoad = ref(true)

// 配置 marked
marked.setOptions({
  highlight: function(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(code, { language: lang }).value
      } catch (e) {
        console.error(e)
      }
    }
    return hljs.highlightAuto(code).value
  },
  breaks: true,
  gfm: true
})

// 渲染 Markdown
const renderMarkdown = (content) => {
  if (!content) return ''
  try {
    return marked(content)
  } catch (e) {
    console.error('Markdown 渲染失败:', e)
    return content
  }
}

// 获取气泡样式类
const getBubbleClass = (msg) => {
  const len = msg.content?.length || 0
  const classes = [msg.role === 'user' ? 'me' : '']
  
  if (len <= 12) classes.push('short')
  else if (len <= 40) classes.push('medium')
  else classes.push('long')
  
  return classes.join(' ')
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesRef.value) {
      messagesRef.value.scrollTop = messagesRef.value.scrollHeight
    }
  })
}

// 保持滚动位置（加载更多历史消息时使用）
const maintainScrollPosition = (previousScrollHeight) => {
  nextTick(() => {
    if (messagesRef.value) {
      const newScrollHeight = messagesRef.value.scrollHeight
      messagesRef.value.scrollTop = newScrollHeight - previousScrollHeight
    }
  })
}

// 滚动事件处理
const handleScroll = () => {
  if (!messagesRef.value || loadingMore.value || !hasMore.value) return
  
  // 当滚动到顶部附近时加载更多
  if (messagesRef.value.scrollTop < 100) {
    loadMoreMessages()
  }
}

// 加载Agent信息
const loadAgent = async () => {
  try {
    const res = await getAgentDetail(agentId.value)
    agentName.value = res.data.name
    agentIcon.value = res.data.name[0]
  } catch (error) {
    console.error(error)
  }
}

// 加载会话列表
const loadSessions = async () => {
  try {
    const res = await getSessions()
    sessions.value = res.data.filter(s => s.agent_id === agentId.value)
    
    if (sessions.value.length === 0) {
      await handleNewSession()
    } else {
      currentSessionId.value = sessions.value[0].id
      await loadMessages()
    }
  } catch (error) {
    console.error(error)
  }
}

// 加载消息（初次加载）
const loadMessages = async () => {
  if (!currentSessionId.value) return
  
  try {
    // 重置分页状态
    currentPage.value = 1
    isFirstLoad.value = true
    
    const res = await getMessages(currentSessionId.value, currentPage.value, pageSize.value)
    messages.value = res.data.messages || []
    hasMore.value = res.data.has_more || false
    
    // 首次加载后滚动到底部
    scrollToBottom()
  } catch (error) {
    console.error(error)
  }
}

// 加载更多历史消息
const loadMoreMessages = async () => {
  if (!currentSessionId.value || loadingMore.value || !hasMore.value) return
  
  try {
    loadingMore.value = true
    
    // 记录当前滚动高度
    const previousScrollHeight = messagesRef.value ? messagesRef.value.scrollHeight : 0
    
    // 加载下一页
    currentPage.value += 1
    const res = await getMessages(currentSessionId.value, currentPage.value, pageSize.value)
    
    // 将新消息插入到开头
    const newMessages = res.data.messages || []
    messages.value = [...newMessages, ...messages.value]
    hasMore.value = res.data.has_more || false
    
    // 保持滚动位置
    maintainScrollPosition(previousScrollHeight)
  } catch (error) {
    console.error(error)
    ElMessage.error('加载消息失败')
  } finally {
    loadingMore.value = false
  }
}

// 新建会话
const handleNewSession = async () => {
  try {
    // 1. 检查是否已存在名为"新会话"的会话
    const existingNewSession = sessions.value.find(s => s.title === '新会话')
    if (existingNewSession) {
      // 如果存在，直接切换到该会话
      currentSessionId.value = existingNewSession.id
      await loadMessages()
      return
    }
    
    // 2. 如果不存在，创建新会话
    const res = await createSession(agentId.value)
    sessions.value.unshift(res.data)
    currentSessionId.value = res.data.id
    messages.value = []
  } catch (error) {
    console.error(error)
  }
}

// 切换会话
const switchSession = async (sessionId) => {
  currentSessionId.value = sessionId
  currentPage.value = 1
  isFirstLoad.value = true
  await loadMessages()
}

// 重命名会话
const handleRenameSession = async (session) => {
  try {
    const { value } = await ElMessageBox.prompt('重命名会话', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: session.title
    })
    
    if (value) {
      await updateSession(session.id, { title: value })
      session.title = value
      ElMessage.success('重命名成功')
    }
  } catch (error) {
    // 用户取消
  }
}

// 发送消息
const handleSend = async (e) => {
  if (e && e.shiftKey) {
    return
  }
  
  if (e) e.preventDefault()
  
  if (!inputMessage.value.trim() || streaming.value) {
    return
  }
  
  const content = inputMessage.value.trim()
  inputMessage.value = ''
  
  // 2. 如果当前会话是"新会话"且是第一条消息，自动重命名
  const currentSession = sessions.value.find(s => s.id === currentSessionId.value)
  if (currentSession && currentSession.title === '新会话' && messages.value.length === 0) {
    // 截取前10个字作为标题
    let newTitle = content.substring(0, 10)
    if (content.length > 10) {
      newTitle += '...'
    }
    
    // 更新会话标题
    try {
      await updateSession(currentSessionId.value, { title: newTitle })
      currentSession.title = newTitle
    } catch (error) {
      console.error('更新会话标题失败:', error)
    }
  }
  
  // 添加用户消息
  messages.value.push({
    id: Date.now(),
    role: 'user',
    content
  })
  scrollToBottom()
  
  // 开始流式接收
  streaming.value = true
  streamingContent.value = ''
  
  try {
    const token = localStorage.getItem('token')
    // EventSource 不支持自定义 headers，需要通过 URL 参数传递 token
    const eventSource = new EventSource(
      `/api/sessions/${currentSessionId.value}/generate/stream?prompt=${encodeURIComponent(content)}&token=${encodeURIComponent(token)}`
    )
    
    eventSource.addEventListener('chunk', (e) => {
      try {
        const data = JSON.parse(e.data)
        streamingContent.value += data.delta || ''
        scrollToBottom()
      } catch (err) {
        console.error('解析chunk失败:', err)
      }
    })
    
    eventSource.addEventListener('final', (e) => {
      try {
        const data = JSON.parse(e.data)
        
        // 添加助手消息
        messages.value.push({
          id: Date.now(),
          role: 'assistant',
          content: streamingContent.value
        })
        
        streamingContent.value = ''
        streaming.value = false
        eventSource.close()
        scrollToBottom()
      } catch (err) {
        console.error('解析final失败:', err)
        streaming.value = false
        eventSource.close()
      }
    })
    
    eventSource.addEventListener('error', (e) => {
      console.error('SSE错误:', e)
      ElMessage.error('生成失败')
      streaming.value = false
      streamingContent.value = ''
      eventSource.close()
    })
    
  } catch (error) {
    console.error(error)
    streaming.value = false
    streamingContent.value = ''
  }
}

watch(() => route.params.agentId, () => {
  loadAgent()
  loadSessions()
})

onMounted(() => {
  loadAgent()
  loadSessions()
})
</script>

<style scoped>
.chat-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f3f6fb;
}

.topbar {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: #2a5085;
  color: #e6edf7;
  border-bottom: 1px solid rgba(147, 197, 253, 0.55);
}

.agent-name {
  font-weight: 600;
  font-size: 16px;
}

.spacer {
  flex: 1;
}

.chat-main {
  display: flex;
  flex: 1;
  gap: 12px;
  padding: 12px;
  overflow: hidden;
}

.sessions-sidebar {
  width: 240px;
  background: #2a5085;
  border-radius: 14px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  color: #e6edf7;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  border-bottom: 1px solid rgba(147, 197, 253, 0.55);
  font-size: 12px;
}

.sessions-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.session-item {
  padding: 10px 12px;
  border-radius: 10px;
  cursor: pointer;
  margin-bottom: 6px;
  border: 1px solid rgba(147, 197, 253, 0.55);
  transition: all 0.15s;
}

.session-item:hover {
  background: rgba(59, 130, 246, 0.06);
}

.session-item.active {
  background: rgba(59, 130, 246, 0.18);
}

.session-title {
  font-size: 14px;
}

.chat-area {
  flex: 1;
  background: #2a5085;
  border-radius: 14px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;           /* 使每条消息行占满整行，便于左右对齐 */
  flex-direction: column;  /* 垂直排列消息 */
}

.load-more-trigger {
  text-align: center;
  padding: 12px 0;
  margin-bottom: 16px;
}

.load-more-trigger .el-button {
  color: #93c5fd;
  font-size: 13px;
}

.load-more-trigger .el-button:hover {
  color: #bfdbfe;
}

.loading-more {
  text-align: center;
  padding: 12px 0;
  margin-bottom: 16px;
  color: #93c5fd;
  font-size: 13px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.loading-more .el-icon {
  font-size: 14px;
}

.msg-line {
  display: flex;
  gap: 12px;
  margin: 12px 0;
  align-items: flex-start;
  width: 100%;
}

/* Agent 消息 - 左侧布局（整行满宽，内容靠左） */
.msg-line:not(.me) {
  justify-content: flex-start;
  flex-direction: row;
}

/* 用户消息 - 右侧布局（整行满宽，内容靠右且贴边） */
.msg-line.me {
  justify-content: flex-end;
  flex-direction: row-reverse;
}

/* 让用户消息气泡贴右边缘 */
.msg-line.me .bubble {
  margin-left: auto;
}

.msg-avatar {
  width: 32px;
  height: 32px;
  border-radius: 999px;
  background: #1e293b;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  color: #93c5fd;
  flex-shrink: 0;
  border: 1px solid rgba(147, 197, 253, 0.55);
}

.msg-avatar.agent {
  background: rgba(59, 130, 246, 0.15);
}

.msg-avatar.user {
  background: rgba(37, 99, 235, 0.20);
  color: #bfdbfe;
}

.bubble {
  display: inline-block;
  max-width: 60%;
  min-width: 80px;
  padding: 12px 16px;
  border-radius: 12px;
  border: 1px solid rgba(147, 197, 253, 0.55);
  background: #2e5f97;
  color: #e6edf7;
  word-break: break-word;
  line-height: 1.6;
}

/* 用户消息气泡 */
.msg-line.me .bubble {
  background: rgba(37, 99, 235, 0.28);
  border-color: rgba(59, 130, 246, 0.4);
}

/* Agent 消息气泡 */
.msg-line:not(.me) .bubble {
  background: #2e5f97;
}

.bubble.streaming {
  background: rgba(59, 130, 246, 0.12);
}

/* Markdown 样式 */
.bubble :deep(p) {
  margin: 0.5em 0;
}

.bubble :deep(p:first-child) {
  margin-top: 0;
}

.bubble :deep(p:last-child) {
  margin-bottom: 0;
}

.bubble :deep(code) {
  background: rgba(0, 0, 0, 0.3);
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.9em;
}

.bubble :deep(pre) {
  background: rgba(0, 0, 0, 0.4);
  padding: 12px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 0.8em 0;
}

.bubble :deep(pre code) {
  background: none;
  padding: 0;
  font-size: 0.85em;
}

.bubble :deep(ul), .bubble :deep(ol) {
  margin: 0.5em 0;
  padding-left: 2em;
}

.bubble :deep(li) {
  margin: 0.3em 0;
}

.bubble :deep(blockquote) {
  border-left: 3px solid rgba(147, 197, 253, 0.55);
  padding-left: 12px;
  margin: 0.8em 0;
  color: rgba(230, 237, 247, 0.8);
}

.bubble :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 0.8em 0;
}

.bubble :deep(th), .bubble :deep(td) {
  border: 1px solid rgba(147, 197, 253, 0.55);
  padding: 8px 12px;
}

.bubble :deep(th) {
  background: rgba(59, 130, 246, 0.15);
}

.bubble :deep(a) {
  color: #93c5fd;
  text-decoration: underline;
}

.bubble :deep(h1), .bubble :deep(h2), .bubble :deep(h3), 
.bubble :deep(h4), .bubble :deep(h5), .bubble :deep(h6) {
  margin: 0.8em 0 0.4em 0;
  font-weight: 600;
}

.bubble :deep(h1:first-child), .bubble :deep(h2:first-child), 
.bubble :deep(h3:first-child) {
  margin-top: 0;
}

.cursor {
  display: inline-block;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.composer {
  display: flex;
  gap: 8px;
  padding: 10px;
  border-top: 1px solid rgba(147, 197, 253, 0.55);
}

.composer .el-textarea {
  flex: 1;
}

:deep(.el-textarea__inner) {
  background: #2e5f97;
  border-color: rgba(147, 197, 253, 0.55);
  color: #e6edf7;
}

:deep(.el-textarea__inner:focus) {
  border-color: rgba(147, 197, 253, 0.8);
}
</style>

